package com.example.wenmini.service;

import com.example.wenmini.entity.Question;
import com.example.wenmini.entity.QuestionOption;
import com.example.wenmini.entity.QuestionType;
import com.example.wenmini.entity.Questionnaire;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class ParseService {
    // 使用Caffeine的Cache在服务端内存中缓存
    private final Cache<String, Questionnaire> questionnaireCache = Caffeine.newBuilder()
            .expireAfterWrite(1, TimeUnit.HOURS)
            .maximumSize(1000)
            .build();

    @Async("parseExecutor")
    public Future<Questionnaire> parseQuestionnaire(String url) {
        // 首先检查缓存
        Questionnaire cached = questionnaireCache.getIfPresent(url);
        if (cached != null) {
            log.info("从缓存中获取问卷数据：{}", url);
            return CompletableFuture.completedFuture(cached);
        }

        try {
            log.info("开始解析问卷，URL：{}", url);

            // 使用Jsoup直接解析网页，无需创建浏览器实例
            Document doc = Jsoup.connect(url)
                    .userAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36")
                    .timeout(10000)
                    .get();

            Questionnaire questionnaire = new Questionnaire();
            questionnaire.setTitle(doc.title());
            questionnaire.setUrl(url);

            List<Question> questions = new ArrayList<>();
            Elements questionElements = doc.select(".field-label");

            for (int i = 0; i < questionElements.size(); i++) {
                Element questionElement = questionElements.get(i);
                Element fieldElement = questionElement.closest(".field");

                Question question = new Question();
                question.setIndex(i + 1);

                // 获取问题标题
                String title = questionElement.select(".topichtml").text();
                if (title.isEmpty()) {
                    title = questionElement.text();
                }
                question.setTitle(title.replaceAll("^\\d+\\.", "").trim());

                // 检查问题类型
                Elements radioOptions = fieldElement.select(".ui-radio");
                Elements checkboxOptions = fieldElement.select(".ui-checkbox");
                Elements textInputs = fieldElement.select("textarea, input[type='text'], input[type='email'], input:not([type])");

                if (!radioOptions.isEmpty()) {
                    question.setType(QuestionType.SINGLE_CHOICE);
                    question.setOptions(parseOptions(radioOptions));
                } else if (!checkboxOptions.isEmpty()) {
                    question.setType(QuestionType.MULTIPLE_CHOICE);
                    question.setOptions(parseOptions(checkboxOptions));
                } else if (!textInputs.isEmpty()) {
                    question.setType(QuestionType.TEXT);
                    question.setOptions(Collections.emptyList());
                }

                question.setHasTextInput(!textInputs.isEmpty());
                questions.add(question);
            }

            questionnaire.setQuestions(questions);

            // 存入缓存
            questionnaireCache.put(url, questionnaire);

            log.info("问卷解析完成，共解析{}个问题", questions.size());
            return CompletableFuture.completedFuture(questionnaire);

        } catch (Exception e) {
            log.error("问卷解析失败：", e);
            throw new RuntimeException("问卷解析失败：" + e.getMessage());
        }
    }

    private List<QuestionOption> parseOptions(Elements optionElements) {
        List<QuestionOption> options = new ArrayList<>();
        for (int i = 0; i < optionElements.size(); i++) {
            Element optElement = optionElements.get(i);
            QuestionOption option = new QuestionOption();
            option.setOptionNumber(i + 1);

            String optionText = optElement.select(".label").text();
            option.setOptionText(optionText);

            // 检查选项是否包含文本输入
            boolean hasTextInput = !optElement.select("textarea, input[type='text'], input[type='email'], input:not([type])").isEmpty();
            option.setHasTextInput(hasTextInput);

            options.add(option);
        }
        return options;
    }
}